package zhklappoint.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import net.sf.json.JSONObject;
import zhklappoint.enums.ENUM_SUCESS;

public class Tools {
	
	public static String password=ResourceUtil.getConfigByName("password");
	public static String isLinux=ResourceUtil.getConfigByName("isLinux");
	//初始化访问类
	private static  CloseableHttpClient httpclient=HttpClients.createDefault();

		//定义匹配script脚本标签的正则表达式
		private final static String reg_script="<script[^>]*?>[\\s\\S]*?<\\/script>";
		//定义匹配style样式的正则表达式
		private final static String reg_style="<style[^>]*?>[\\s\\S]*?<\\/style>";
		//定义匹配html标签的正则表达式
		private final static String reg_html="<[.[^>]]*>";
		//定义匹配空格的正则表达式
		private final static String reg_space="\\s*|\t|\r|\n";

	
		//图片路径拼装
		/***
		 * 
		 * @param imgName 图片命名
		 * @param imgPath 图片上级路径
		 * @param folderName 图片所在目录路径
		 * @param isPrivacy  是否为私密图片
		 * @return
		 */
		public static String splitString(String imgName,String imgPath, String folderName,Integer isPrivacy) {
			 String urlopen = ResourceUtil.getConfigByNameNeed("serverUrl");
			 String urlprivacy = ResourceUtil.getConfigByNameNeed("serverPrivacy");
			 String url="";
			 if(isPrivacy==0) {
				 url=urlopen+imgPath+"/"+folderName+"/"+imgName;
			 }else {
				 url=urlprivacy+imgPath+"/"+folderName+"/"+imgName;
			 }
			return url;
		}
		//图片路径返回
				/***
				 * 
				 * @param imgName 图片命名
				 * @param imgPath 图片上级路径
				 * @param folderName 图片所在目录路径
				 * @param isPrivacy  是否为私密图片
				 * @return
				 */
				public static String splitString(String imgPath, String folderName,Integer isPrivacy) {
					 String urlopen = ResourceUtil.getConfigByNameNeed("serverUrl");
					 String urlprivacy = ResourceUtil.getConfigByNameNeed("serverPrivacy");
					 String url="";
					 if(isPrivacy==0) {
						 url=urlopen+imgPath+"/"+folderName+"/";
					 }else {
						 url=urlprivacy+imgPath+"/"+folderName+"/";
					 }
					return url;
				}
		//图片上传功能
		/***
		 * 
		 * @param file   上传文件
		 * @param imgPath  图片所在文件名路径
		 * @param folderName  图片所在文件
		 * @param isPrivacy  是否私密0可以被外界查看的普通照片  1不允许外界查看的图片  isPrivacy
		 * @param fileName 文件名称如果不传随机生成
		 * @return
		 */
    public static String getImageUrl(MultipartFile file,String imgPath, String folderName,Integer isPrivacy,String fileName){
        if(!ObjectUtils.isEmpty(file)){
        	if(file.getSize()>1024000*3) {
        		return "0";
        	}
            if(ObjectUtils.isEmpty(fileName)) {
            	fileName="appoint_"+ UUID.randomUUID().toString().replace("-", "");//自己写方法获取随机数作为新文件名
            }
            String imgUrl=file.getOriginalFilename();
//            String fileName_wei = file.getOriginalFilename().split("\\.")[1];//获取文件名后缀
            String fileName_wei = imgUrl.substring(imgUrl.lastIndexOf(".")+1);
            String fileName_New = fileName+"."+fileName_wei;//新文件名
            String filePath = "";
                try {
                    // 文件保存路径  File.separator（linux与windows路径分隔符不一样，用java获取）
                	if(isLinux.equals("2")) {
                		if(isPrivacy==1) {
                			filePath="/data/privacyInfo/img/wxmall/"+imgPath+"/"+folderName;//linux
                		}else {
                			filePath="/data/show/img/wxmall/"+imgPath+"/"+folderName;//linux
                		}
                		
                	}else if(isLinux.equals("1")) {
                		filePath="D:\\myselfSpace\\zhkl_appoint\\src\\main\\resources\\static\\"+imgPath+"\\"+folderName;//windows
                	}
                    File f=new File(filePath);
                    if(!f.exists()) {
                        f.mkdir();
                    }
                    file.transferTo(new File(filePath+f.separator+fileName_New));
                } catch (Exception e) {
//                    return null;
                    e.printStackTrace();
                }
            return fileName_New;
        }
        return "";
    }
    /***
     * base64图片上传
     * @param powerList
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String uploadBase64Image(String imgPath, String folderName,String base64Data,Integer isPrivacy,String fileName) throws Exception {
    	String realPath="";
        String dataPrix = "";// 图片格式
        String data = "";// 图片内容
        String[] d = base64Data.split("base64,");
        if(d==null||d.length!=2) {
        	return "250";
        }
        if (d != null && d.length == 2) {
            dataPrix = d[0];
            data = d[1];
        }
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)
                || "data:image/jpg;".equalsIgnoreCase(dataPrix)) {// 编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {// 编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {// 编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {// 编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception("上传图片格式不合法");
        }
        // 因为BASE64Decoder的jar问题，此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        //限制文件大小为1m以内
//        System.out.println(bs.length);
        if(bs.length > 1024*1024*1){
            return "0";
        }
        // 文件保存路径  File.separator（linux与windows路径分隔符不一样，用java获取）
    	if(isLinux.equals("2")) {
    		if(isPrivacy==1) {
    			realPath="/data/privacyInfo/img/wxmall/"+imgPath+"/"+folderName;//linux
    		}else {
    			realPath="/data/show/img/wxmall/"+imgPath+"/"+folderName;//linux
    		}
    			
    	}else if(isLinux.equals("1")) {
    		realPath="D:\\myselfSpace\\zhkl_appoint\\src\\main\\resources\\static\\"+imgPath+"\\"+folderName;//windows
    	}
        
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdir();
        }
        // 新文件名格式：项目根路径+upload+日期+uuid+后缀名
        if(ObjectUtils.isEmpty(fileName)) {
        	fileName="appointor_"+ UUID.randomUUID().toString().replace("-", "");//自己写方法获取随机数作为新文件名
        }
        String newFileName = new StringBuffer(fileName).append(suffix).toString();
        try {
            // 使用apache提供的工具类操作流
            FileUtils.writeByteArrayToFile(new File(realPath + "/" + newFileName), bs);
        } catch (Exception ee) {
            throw new Exception("上传失败，写入文件失败，" + ee.getMessage());
        }
        return newFileName;
    }
    
    
    //session存储操作权限
    public static List<String> getPageContentVo(String powerList) throws UnsupportedEncodingException{
    	List<String> ls = new ArrayList<String>();
    	if(ObjectUtils.isEmpty(powerList)) {
    		return ls;
    	}
    	 byte[] decode = parseHexStr2Byte(powerList);
         // 解密
         byte[] decryptResult = decrypt(decode, password);
    	String data = new String(decryptResult, "UTF-8");
    	String[] pl = data.split(",");
    	for(int i=0;i<pl.length;i++) {
    		ls.add(pl[i]);
    	}
		return ls;
    }
    
    /**
     * 加密
     * 
     * @param content
     *            需要加密的内容
     * @param password
     *            加密密码
     * @return
     */
    public static byte[] encrypt(String content, String password) {
    	if(isLinux.equals("2")) {
    		return encrypt2(content, password);
    	}else {
    		return encrypt1(content, password);
    	}
    }
    //linux
    public static byte[] encrypt2(String content, String password) {
        try {
        	SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(password.getBytes());
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
    //wnidows
    public static byte[] encrypt1(String content, String password) {
    	try {
    		KeyGenerator kgen = KeyGenerator.getInstance("AES");
    		kgen.init(128, new SecureRandom(password.getBytes()));
    		SecretKey secretKey = kgen.generateKey();
    		byte[] enCodeFormat = secretKey.getEncoded();
    		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
    		Cipher cipher = Cipher.getInstance("AES");// 创建密码器
    		byte[] byteContent = content.getBytes("utf-8");
    		cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
    		byte[] result = cipher.doFinal(byteContent);
    		return result; // 加密
    	} catch (NoSuchAlgorithmException e) {
    		e.printStackTrace();
    	} catch (NoSuchPaddingException e) {
    		e.printStackTrace();
    	} catch (InvalidKeyException e) {
    		e.printStackTrace();
    	} catch (UnsupportedEncodingException e) {
    		e.printStackTrace();
    	} catch (IllegalBlockSizeException e) {
    		e.printStackTrace();
    	} catch (BadPaddingException e) {
    		e.printStackTrace();
    	}
    	return null;
    }
    /**
     * 将二进制转换成16进制
     * 
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    
    /**
     * 将16进制转换为二进制
     * 
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    
    /**
     * 解密
     * 
     * @param content
     *            待解密内容
     * @param password
     *            解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String password) {
    	if(isLinux.equals("2")) {
    		return decrypt2(content, password);
    	}else{
    		return decrypt1(content, password);
    	}
    		
    }
    //wnidows
    public static byte[] decrypt1(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
    //linux
    public static byte[] decrypt2(byte[] content, String password) {
    	try {
    		KeyGenerator kgen = KeyGenerator.getInstance("AES");
    		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
    		kgen.init(128, random);
    		SecretKey secretKey = kgen.generateKey();
    		byte[] enCodeFormat = secretKey.getEncoded();
    		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
    		Cipher cipher = Cipher.getInstance("AES");// 创建密码器
    		
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
    	} catch (NoSuchAlgorithmException e) {
    		e.printStackTrace();
    	} catch (NoSuchPaddingException e) {
    		e.printStackTrace();
    	} catch (InvalidKeyException e) {
    		e.printStackTrace();
    	} catch (IllegalBlockSizeException e) {
    		e.printStackTrace();
    	} catch (BadPaddingException e) {
    		e.printStackTrace();
    	}
    	return null;
    }
  //删除标签
    public static String delTag(String htmlStr) {  
                //创建模式,CASE_INSENSITIVE静态常量可以忽略大小写
                Pattern p_script = Pattern.compile(reg_script, Pattern.CASE_INSENSITIVE);  
                //创建适配器完成匹配,被匹配中的变成空串
                Matcher m_script = p_script.matcher(htmlStr);// 过滤script标签  
                //替换所有空串,达到删除的效果
                htmlStr = m_script.replaceAll(""); 

                Pattern p_style = Pattern.compile(reg_style, Pattern.CASE_INSENSITIVE);  
                Matcher m_style = p_style.matcher(htmlStr);  // 过滤style标签  
                htmlStr = m_style.replaceAll(""); 

                Pattern p_html = Pattern.compile(reg_html, Pattern.CASE_INSENSITIVE);  
                Matcher m_html = p_html.matcher(htmlStr);  // 过滤html标签  
                htmlStr = m_html.replaceAll(""); 

                Pattern p_space = Pattern.compile(reg_space, Pattern.CASE_INSENSITIVE);  
                Matcher m_space = p_space.matcher(htmlStr);  // 过滤空格回车标签
                htmlStr = m_space.replaceAll("");   
                return htmlStr.trim(); // 返回文本字符串  
            }
    /**
	 * 用SHA1算法生成安全签名
	 * @param token 票据
	 * @param timestamp 时间戳
	 * @param nonce 随机字符串
	 * @param encrypt 密文
	 * @return 安全签名
	 * @throws AesException 
	 */
	public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException
			  {
		try {
			String[] array = new String[] { token, timestamp, nonce, encrypt };
			StringBuffer sb = new StringBuffer();
			// 字符串排序
			Arrays.sort(array);
			for (int i = 0; i < 4; i++) {
				sb.append(array[i]);
			}
			String str = sb.toString();
			// SHA1签名生成
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(str.getBytes());
			byte[] digest = md.digest();

			StringBuffer hexstr = new StringBuffer();
			String shaHex = "";
			for (int i = 0; i < digest.length; i++) {
				shaHex = Integer.toHexString(digest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexstr.append(0);
				}
				hexstr.append(shaHex);
			}
			return hexstr.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw new AesException(AesException.ComputeSignatureError);
		}
	}
	public static String getSHACheck(String token, String timestamp, String nonce) throws AesException
				  {
			try {
				String[] array = new String[] { token, timestamp, nonce};
				StringBuffer sb = new StringBuffer();
				// 字符串排序
				Arrays.sort(array);
				for (int i = 0; i < 3; i++) {
					sb.append(array[i]);
				}
				String str = sb.toString();
				// SHA1签名生成
				MessageDigest md = MessageDigest.getInstance("SHA-1");
				md.update(str.getBytes());
				byte[] digest = md.digest();
			
				StringBuffer hexstr = new StringBuffer();
				String shaHex = "";
				for (int i = 0; i < digest.length; i++) {
					shaHex = Integer.toHexString(digest[i] & 0xFF);
					if (shaHex.length() < 2) {
						hexstr.append(0);
					}
					hexstr.append(shaHex);
				}
				return hexstr.toString();
			} catch (Exception e) {
				e.printStackTrace();
				throw new AesException(AesException.ComputeSignatureError);
			}
			}
	public static String getHttpPost(String url, List<NameValuePair> list) {
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(8000).setConnectTimeout(8000).build();
        httpPost.setConfig(requestConfig);
		httpPost.setEntity(new UrlEncodedFormEntity(list,StandardCharsets.UTF_8));
		String data = "";
		 // 执行请求
        try {
            HttpResponse resp = httpclient.execute(httpPost);
            // 判断是否响应成功
            if (resp.getStatusLine().getStatusCode() == 200) {
                // 获取响应 的数据
                HttpEntity entity = resp.getEntity();

                data = EntityUtils.toString(entity, "utf-8");
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return data;
	}
	
	public static String getHttpGet(String url,String token) {
        String data = "";
        // 设置参数
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(8000).setConnectTimeout(8000).build();
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("T-Zhkl-Token", token);
        // 执行请求
        try {
            HttpResponse resp = httpclient.execute(httpGet);
            // 判断是否响应成功
            if (resp.getStatusLine().getStatusCode() == 200) {
                // 获取响应 的数据
                HttpEntity entity = resp.getEntity();
                data = EntityUtils.toString(entity, "utf-8");
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return data;
    }
	
	public static String bodyPost(String actionUrl, JSONObject params) throws IOException {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--";
        String LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(30 * 1000); // 缓存的最长时间
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
        String sb = "";
        if (params!=null) {
            // 首先组拼文本类型的参数
//            for (Map.Entry<String, String> entry : params.entrySet()) {
//                sb.append(PREFIX);
//                sb.append(BOUNDARY);
//                sb.append(LINEND);
//                sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"" + LINEND);
//                sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
//                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
//                sb.append(LINEND);
//                sb.append(entry.getValue());
//                sb.append(LINEND);
//            }
        	sb=params.toString();
        }
        System.out.println("s---------------:"+sb);
        DataOutputStream outStream = new DataOutputStream(
                conn.getOutputStream());
        if (!TextUtils.isEmpty(sb.toString())) {
            outStream.write(sb.toString().getBytes());
        }
        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();

        // 得到响应码
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        if (res == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null){
                buffer.append(line);
            }

//          int ch;
//          StringBuilder sb2 = new StringBuilder();
//          while ((ch = in.read()) != -1) {
//              sb2.append((char) ch);
//          }
            return buffer.toString();
        }
        outStream.close();
        conn.disconnect();
        return in.toString();
    }
	//获取用户的ip真实地址
	public static String getIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for"); 
        if (!ObjectUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {  
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("X-Real-IP");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        } 
        return ip;  
    }
	//微信支付根据签名加密获取参数
	public static String arraySign(Map<Object, Object> params, String paySignKey) {
        boolean encode = false;
        Set<Object> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = value.toString();
            }
            if (encode) {
                try {
                    temp.append(URLEncoder.encode(valueString, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                temp.append(valueString);
            }
        }
        if(!ObjectUtils.isEmpty(paySignKey)) {
        	temp.append("&key=");
            temp.append(paySignKey);
        }
        System.out.println(temp.toString());
        String packageSign = getMessageDigest(temp.toString());
        return packageSign;
    }
	 public static String getMessageDigest(String data) {//md5加密
	        StringBuilder sb = new StringBuilder();
	        try {
	            MessageDigest md = MessageDigest.getInstance("MD5");
	            byte[] array = md.digest(data.getBytes("UTF-8"));

	            for (byte item : array) {
	                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
	            }
	        } catch (Exception e) {
	            return null;
	        }
	        return sb.toString().toUpperCase();
	    }
	 //map转xml
	 public static String convertMap2Xml(Map<Object, Object> paraMap) {
	        StringBuffer xmlStr = new StringBuffer();
	        if (paraMap != null) {
	            xmlStr.append("<xml>");
	            Set<Object> keySet = paraMap.keySet();
	            Iterator<Object> keyIte = keySet.iterator();
	            while (keyIte.hasNext()) {
	                String key = (String) keyIte.next();
	                String val = String.valueOf(paraMap.get(key));
	                xmlStr.append("<");
	                xmlStr.append(key);
	                xmlStr.append(">");
	                xmlStr.append(val);
	                xmlStr.append("</");
	                xmlStr.append(key);
	                xmlStr.append(">");
	            }
	            xmlStr.append("</xml>");
	        }
	        return xmlStr.toString();
	    }
	 //单次请求 不重复调用
	 public static String requestOnce(final String url, String data) throws Exception {
	        BasicHttpClientConnectionManager connManager;
	        connManager = new BasicHttpClientConnectionManager(
	                RegistryBuilder.<ConnectionSocketFactory>create()
	                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
	                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
	                        .build(),
	                null,
	                null,
	                null
	        );

	        HttpClient httpClient = HttpClientBuilder.create()
	                .setConnectionManager(connManager)
	                .build();

	        HttpPost httpPost = new HttpPost(url);

	        RequestConfig requestConfig = RequestConfig.custom()
	                .setSocketTimeout(5000)
	                .setConnectTimeout(5000)
	                .setConnectionRequestTimeout(10000).build();

	        httpPost.setConfig(requestConfig);

	        StringEntity postEntity = new StringEntity(data, "UTF-8");
	        httpPost.addHeader("Content-Type", "text/xml");
	        httpPost.addHeader("User-Agent", "wxpay sdk java v1.0 " + ResourceUtil.getConfigByName("wx.mchId"));
	        httpPost.setEntity(postEntity);

	        HttpResponse httpResponse = httpClient.execute(httpPost);
	        HttpEntity httpEntity = httpResponse.getEntity();
	        String reusltObj = EntityUtils.toString(httpEntity, "UTF-8");
//	        logger.info("请求结果:" + reusltObj);
	        System.out.println("请求结果:" + reusltObj);
	        return reusltObj;
	    }
	 /**
	     * 将xml格式的字符串转换成Map对象
	     *
	     * @param xmlStr xml格式的字符串
	     * @return Map对象
	     * @throws Exception 异常
	     */
	    public static Map<String, Object> xmlStrToMap(String xmlStr) throws Exception {
	        if (ObjectUtils.isEmpty(xmlStr)) {
	            return null;
	        }
	        Map<String, Object> map = new HashMap<String, Object>();
	        // 将xml格式的字符串转换成Document对象
	        Document doc = DocumentHelper.parseText(xmlStr);
	        // 获取根节点
	        Element root = doc.getRootElement();
	        // 获取根节点下的所有元素
	        List children = root.elements();
	        // 循环所有子元素
	        if (children != null && children.size() > 0) {
	            for (int i = 0; i < children.size(); i++) {
	                Element child = (Element) children.get(i);
	                map.put(child.getName(), child.getTextTrim());
	            }
	        }
	        return map;
	    }
	    //获取到map中某个键的值
	    public static String getString(String key, Map<String, Object> map) {
	        if (map == null || key == null)
	            throw new IllegalArgumentException();
	        if (!map.containsKey(key))
	            return null;
	        Object value = map.get(key);
	        if (value == null)
	            return null;
	        return value.toString();
	    }
	    /**
	     * xml字符串转换成bean对象
	     *
	     * @param xmlStr xml字符串
	     * @param clazz  待转换的class
	     * @return 转换后的对象
	     */
	    public static Object xmlStrToBean(String xmlStr, Class clazz) {
	        Object obj = null;
	        try {
	            // 将xml格式的数据转换成Map对象
	            Map<String, Object> map = xmlStrToMap(xmlStr);
	            // 将map对象的数据转换成Bean对象
	            obj = mapToBean(map, clazz);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return obj;
	    }
	    /**
	     * 将Map对象通过反射机制转换成Bean对象
	     *
	     * @param map   存放数据的map对象
	     * @param clazz 待转换的class
	     * @return 转换后的Bean对象
	     * @throws Exception 异常
	     */
	    public static Object mapToBean(Map<String, Object> map, Class clazz) throws Exception {
	        Object obj = clazz.newInstance();
	        if (map != null && map.size() > 0) {
	            for (Map.Entry<String, Object> entry : map.entrySet()) {
	                String propertyName = entry.getKey();
	                Object value = entry.getValue();
	                String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
	                Field field = getClassField(clazz, propertyName);
	                if (field != null) {
	                    Class fieldTypeClass = field.getType();
	                    value = convertValType(value, fieldTypeClass);
	                    clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
	                }
	            }
	        }
	        return obj;
	    }
	    /**
	     * 获取指定字段名称查找在class中的对应的Field对象(包括查找父类)
	     *
	     * @param clazz     指定的class
	     * @param fieldName 字段名称
	     * @return Field对象
	     */
	    private static Field getClassField(Class clazz, String fieldName) {
	        if (Object.class.getName().equals(clazz.getName())) {
	            return null;
	        }
	        Field[] declaredFields = clazz.getDeclaredFields();
	        for (Field field : declaredFields) {
	            if (field.getName().equals(fieldName)) {
	                return field;
	            }
	        }

	        Class superClass = clazz.getSuperclass();
	        if (superClass != null) {// 简单的递归一下
	            return getClassField(superClass, fieldName);
	        }
	        return null;
	    }
	    /**
	     * 将Object类型的值，转换成bean对象属性里对应的类型值
	     *
	     * @param value          Object对象值
	     * @param fieldTypeClass 属性的类型
	     * @return 转换后的值
	     */
	    private static Object convertValType(Object value, Class fieldTypeClass) {
	        Object retVal = null;
	        if (Long.class.getName().equals(fieldTypeClass.getName())
	                || long.class.getName().equals(fieldTypeClass.getName())) {
	            retVal = Long.parseLong(value.toString());
	        } else if (Integer.class.getName().equals(fieldTypeClass.getName())
	                || int.class.getName().equals(fieldTypeClass.getName())) {
	            retVal = Integer.parseInt(value.toString());
	        } else if (Float.class.getName().equals(fieldTypeClass.getName())
	                || float.class.getName().equals(fieldTypeClass.getName())) {
	            retVal = Float.parseFloat(value.toString());
	        } else if (Double.class.getName().equals(fieldTypeClass.getName())
	                || double.class.getName().equals(fieldTypeClass.getName())) {
	            retVal = Double.parseDouble(value.toString());
	        } else {
	            retVal = value;
	        }
	        return retVal;
	    }
		/***
		 * 把地址格式URLencode转换
		 */
		public static String changeUrlToDataURLencode(String url){
			try {
				url=URLEncoder.encode(url,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return url;
		}
		//验证ip地址是否境内
		public static Boolean checkIPNotForeign(String ip) {
			if(ip.equals("0:0:0:0:0:0:0:1")) {
				return true;
			}
			Boolean b=false;//https://ip.taobao.com/ipSearch?ipAddr=125.80.225.207
			Long t=new Date().getTime();
			String url = "http://opendata.baidu.com/api.php?query="+ip+"&co=&resource_id=6006&t="+t+"&ie=utf8&oe=utf-8&format=json";//+ip
			try {
	            //发送get请求
	            HttpGet request = new HttpGet(url);
	            HttpResponse response = httpclient.execute(request);
	            /**请求发送成功，并得到响应**/
	            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	                /**读取服务器返回过来的json字符串数据**/  
	                String strResult = EntityUtils.toString(response.getEntity());
	                Map<String,Object> map=JSONObject.fromObject(strResult);
	                if(Integer.valueOf(map.get("status")+"")!=0) {
	                	return false;
	                }
	                Map<String,Object> map1=new HashMap<String,Object>();
	                net.sf.json.JSONArray  jas =net.sf.json.JSONArray.fromObject(map.get("data")+"");
	                
	                map1=JSONObject.fromObject(jas.get(0)+"");
	                map.clear();
	                for(Entry e : map1.entrySet()){
	                	map.put(e.getKey().toString(),e.getValue());
	                }
	                Boolean bolean=false;
                	String urlType="移动,联通,电信,铁通,局域网,广电,网通";
                	String[] arrStr=urlType.split(",");
                	String urlNow=map.get("location")+"";
                	for(int i=0;i<arrStr.length;i++){
                		if(urlNow.contains(arrStr[i])){
                			bolean=true;
                			break;
                		}
                	}
                	if(bolean){
                		b=true;
                	}
	            }
	        }
	        catch (IOException e) {
	            e.printStackTrace();
	        }
			return b;
		}
		
				
				//post请求方法
				public static  String weChatPost(String url, JSONObject param) {
					System.out.println("param:"+param);
					HttpPost httpPost = new HttpPost(url);
					HttpResponse resp = null;
					try {
						StringEntity entityParams = new StringEntity(param.toString(),"utf-8");  
						httpPost.setEntity(entityParams);
						
						resp = httpclient.execute(httpPost);
						System.out.println("resp::"+resp);
						if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
							return null;
						}
						return EntityUtils.toString(resp.getEntity(), "UTF-8");
					} catch (Exception e) {
						e.printStackTrace();
						return null;
					}
				}
				//get请求方法
				public static  String weChatGet(String url,String types) {
					Map<String,Object> map=new HashMap<String,Object>();
					HttpGet httpGet = new HttpGet(url);
					try {
						HttpResponse resp = httpclient.execute(httpGet);
						if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
					        map.put("status",ENUM_SUCESS.FAILED.value);
					        map.put("msg", types+"获取失败!");
							return JSON.toJSONString(map);
						}
						map.put("data",EntityUtils.toString(resp.getEntity(), "UTF-8"));
				        map.put("status", ENUM_SUCESS.SUCESS.value);
						return JSON.toJSONString(map);
					} catch (Exception e) {
						e.printStackTrace();
						 map.put("status",ENUM_SUCESS.FAILED.value);
					     map.put("msg", types+"获取失败!");
						return JSON.toJSONString(map);
					}
				}
				
				  /**
			     * 生成 HMACSHA256
			     * @param data 待处理数据
			     * @param key 密钥
			     * @return 加密结果
			     * @throws Exception
			     */
			    public static String HMACSHA256(String data, String key) throws Exception {
			        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
			        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
			        sha256_HMAC.init(secret_key);
			        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
			        StringBuilder sb = new StringBuilder();
			        for (byte item : array) {
			            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
			        }
			        return sb.toString().toUpperCase();
			    }
			    /***
			     * 判断一个字符串中是否全是数字
			     * @param str
			     * @return
			     */
			    public static boolean isNumeric(String str){
			        Pattern pattern = Pattern.compile("[0-9]*"); 
			        return pattern.matcher(str).matches();    
			    }
			    
			    /**
			     * 大陆号码或香港号码均可
			     */
			    public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
			        return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
			    }
			 
			    /**
			     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
			     * 此方法中前三位格式有：
			     * 13+任意数
			     * 145,147,149
			     * 15+除4的任意数(不要写^4，这样的话字母也会被认为是正确的)
			     * 166
			     * 17+3,5,6,7,8
			     * 18+任意数
			     * 198,199
			     */
			    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
			        // ^ 匹配输入字符串开始的位置
			        // \d 匹配一个或多个数字，其中 \ 要转义，所以是 \\d
			        // $ 匹配输入字符串结尾的位置
//			        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
//			                "|(18[0-9])|(19[8,9]))\\d{8}$";
			    	String regExp = "^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])" +
				                "|(18[0-9])|(19[0-9]))\\d{8}$";
			        Pattern p = Pattern.compile(regExp);
			        Matcher m = p.matcher(str);
			        return m.matches();
			    }
			 
			    /**
			     * 香港手机号码8位数，5|6|8|9开头+7位任意数
			     */
			    public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
			        // ^ 匹配输入字符串开始的位置
			        // \d 匹配一个或多个数字，其中 \ 要转义，所以是 \\d
			        // $ 匹配输入字符串结尾的位置
			        String regExp = "^(5|6|8|9)\\d{7}$";
			        Pattern p = Pattern.compile(regExp);
			        Matcher m = p.matcher(str);
			        return m.matches();
			    }
}
